package com.ubi.core.framework.job;

import com.ubi.core.utils.DateUtils;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.support.CronSequenceGenerator;

import java.util.Date;

public final class JobSetting {

    private SchedulerJob schedulerJob;

    private String jobName;

    private String cronExpression;

    private boolean enable;

    private boolean loopTenants;

    private Date lastExecuteTime;

    private JobSetting() {
    }

    public static JobSetting getJobSetting(Environment environment, SchedulerJob schedulerJob) {
        JobSetting jobSetting = new JobSetting();

        jobSetting.setSchedulerJob(schedulerJob);

        String classSimpleName = schedulerJob.getClass().getSimpleName();
        jobSetting.setJobName(classSimpleName);

        String cronExpression = environment.getProperty("scheduler." + classSimpleName + ".cron");
        jobSetting.setCronExpression(cronExpression);

        if (cronExpression != null) {
            CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cronExpression);
            jobSetting.setLastExecuteTime(cronSequenceGenerator.next(DateUtils.addDay(new Date(), -1)));
        }

        jobSetting.setEnable(
            environment.getProperty("scheduler." + classSimpleName + ".enable", Boolean.class, Boolean.TRUE));
        return jobSetting;
    }

    public SchedulerJob getSchedulerJob() {
        return schedulerJob;
    }

    public void setSchedulerJob(SchedulerJob schedulerJob) {
        this.schedulerJob = schedulerJob;
    }

    public String getJobName() {
        return jobName;
    }

    public void setJobName(String jobName) {
        this.jobName = jobName;
    }

    public String getCronExpression() {
        return cronExpression;
    }

    public void setCronExpression(String cronExpression) {
        this.cronExpression = cronExpression;
    }

    public boolean isEnable() {
        return enable;
    }

    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    public boolean isLoopTenants() {
        return loopTenants;
    }

    public void setLoopTenants(boolean loopTenants) {
        this.loopTenants = loopTenants;
    }

    public Date getLastExecuteTime() {
        return lastExecuteTime;
    }

    public void setLastExecuteTime(Date lastExecuteTime) {
        this.lastExecuteTime = lastExecuteTime;
    }
}
